package com.idak.spring.web.flow;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class SearchCriteriaServiceImpl implements SearchCriteriaService {

	private List<Person> persons;
	
	public SearchCriteriaServiceImpl() {
		
		persons = new ArrayList<Person>();
		
		Person p1 = new Person(new Long(1),"KADI","Abdelhamid","0106060708","idak@gmail.com");
		Person p2 = new Person(new Long(2),"KADI","Ines","0606060708","idak2@gmail.com");
		Person p3 = new Person(new Long(3),"KADI","Nour","0706060708","idak3@gmail.com");
		
		persons.add(p1);
		persons.add(p2);
		persons.add(p3);
	}

	@Override
	public List<Person> serach(SearchCriteria searchCriteria) {
		List<Person> result = new ArrayList<Person>();
		for (Person person : persons) {
			if (StringUtils.hasText(searchCriteria.getFirstName())&& StringUtils.hasText(searchCriteria.getLastName())){
					if(person.getLastName().equals(searchCriteria.getLastName())&& person.getFirstName().equals(searchCriteria.getFirstName())) {
						result.add(person);
					}
			}else {
				if (person.getLastName().equals(searchCriteria.getLastName())
		           || person.getFirstName().equals(searchCriteria.getFirstName())) {
					result.add(person);
				}
			}
		}
		return result;
	}

	@Override
	public Person getPerson(Long personId) {
		Person person = null;
		for (Person p : persons) {
			if(personId.longValue() == p.getPersonId().longValue()){
				person = new Person(p.getPersonId(), p.getLastName(), p.getFirstName(), p.getPhoneNumber(), p.getEmail());
			}
		}
		return person;
	}

}
